﻿using System;
using System.Windows.Forms;
using TimeTable.Domain.DataAccess;
using TimeTable.Domain.Entity;

namespace TimeTable.AddForms
{
    public partial class NewStudyUnitForm : Form
    {
        private readonly StudyUnitType _type;

        public NewStudyUnitForm(StudyUnitType type)
        {
            InitializeComponent();

            _type = type;

            switch (type)
            {
                case StudyUnitType.Stream:
                {
                    Text = "New stream";
                    parentLabel.Visible = false;
                    parent.Visible = false;
                    break;
                }
                case StudyUnitType.Group:
                {
                    Text = "New group";
                    parent.DataSource = DataAccessConnection.Instance.GetStudyUnitsByType(StudyUnitType.Stream);
                    break;
                }
            }

            faculty.DataSource = DataAccessConnection.Instance.GetDivisionsByType(DivisionType.Faculty);
        }

        private void CancelButtonClick(object sender, EventArgs e)
        {
            Close();
        }

        private void OKButtonClick(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(name.Text)) throw new Exception("Name can not be empty!");

                var division = faculty.SelectedItem as Division;
                if (division == null) throw new Exception("Please select faculty!");

                var studyUnit = new StudyUnit
                {
                    Name = name.Text,
                    StudentsNumber = Convert.ToInt32(studentsNumber.Value),
                    Division = division,
                    Type = _type
                };

                if (_type != StudyUnitType.Stream)
                {
                    var unit = parent.SelectedItem as StudyUnit;
                    if (unit == null) throw new Exception("Please select parent study unit!");

                    studyUnit.Parent = unit;
                }
                
                DataAccessConnection.Instance.AddStudyUnit(studyUnit);

                MessageBox.Show("Study unit successfully added!");

                Close();
            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.Message, "Error");
            }
        }
    }
}
